﻿window.bookApp.bookViewModel = (function (ko, datacontext) {

    var bookViews = ["My Books", "By Titles", "By Authors", "By Genres"],
        chosenView = ko.observable(),
        books = ko.observableArray(),
        book = ko.observable(),
        error = ko.observable(),
        addBook = function() {
            var newBook = datacontext.createBook();

            datacontext.saveNewBook(newBook)
                .then(addSucceeded)
                .fail(addFailed);

            function addSucceeded() {
                showBook(newBook);
            }

            function addFailed() {
                error("Save of new Book failed");
            }
        },
        showBook = function(newBook) {
            books.unshift(newBook); // Insert new Book at the front
        },
        deleteBook = function(newBook) {
            books.remove(newBook);
            datacontext.deleteBook(newBook)
                .fail(deleteFailed);

            function deleteFailed() {
                showBook(newBook); // re-show the restored list
            }
        },
        editBook = function(newBook) {
            book(newBook);
            books(null);
        },
        doneEdit = function(newBook) {
            book(null);
            datacontext.getBooks(books, error);
        };
        
    
    datacontext.getBooks(books, error); // load Books

    return {
        bookViews: bookViews,
        chosenView: chosenView,
        books: books,
        book: book,
        error: error,
        addBook: addBook,
        deleteBook: deleteBook,
        editBook: editBook,
        doneEdit: doneEdit
    };

})(ko, bookApp.datacontext);

// Initiate the Knockout bindings
ko.applyBindings(window.bookApp.bookViewModel);
